package com.liyuan.yiqixing.component.security;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
public class DisableUrlSessionIdFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(!(servletRequest instanceof HttpServletRequest)){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse= (HttpServletResponse) servletResponse;
        if(httpServletRequest.isRequestedSessionIdFromURL()){
            HttpSession session = httpServletRequest.getSession();
            if(session!=null){
                session.invalidate();
            }
        }
        HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(httpServletResponse){
            @Override
            public String encodeRedirectURL(String url) {
                return url;
            }

            @Override
            public String encodeURL(String url) {
                return url;
            }
        };
        filterChain.doFilter(servletRequest,responseWrapper);
    }
}
